import { http } from '@kit.NetworkKit';
import { promptAction } from '@kit.ArkUI';


export class ResponsesData<T> {
  status: number = 0
  msg: string = ""
  data: T | null = null
}

interface EmptyInterface {}

const BASE_URL = 'https://m.maizuo.com'

async function requestHttp<T>(
  url: string = '',
  method: http.RequestMethod = http.RequestMethod.GET,
  data?: object,
  host: string = ''
): Promise<T> {
  const httpRequest = http.createHttp()
  let urlStr = BASE_URL + url

  if (method === http.RequestMethod.GET && Object.keys(data)?.length > 0) {
    urlStr += "?" + Object.keys(data).map(key => data[key] ? `${key}=${data[key]}` : '').join('&')
  }

  //设置请求对象
  const config: http.HttpRequestOptions = {
    method,
    readTimeout: 10000,
    extraData: method === http.RequestMethod.GET ? '' : data || {} as EmptyInterface,
    header: {
      "X-Host": host,
      'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"1596502176387264316178433","bc":"310100"}'
    }
  }

  try {
    const res = await httpRequest.request(urlStr, config)

    if (res.responseCode === 401) {
      promptAction.showToast({ message: 'token超时！' })
      // 返回登录
      return Promise.reject(new Error('token超时！'))
    }

    if (res.responseCode === 404) {
      promptAction.showToast({ message: '请求地址不正确！' })
      return Promise.reject(new Error('请求地址不正确！'))
    }

    const result = JSON.parse(res.result as string) as ResponsesData<T>

    if (res.responseCode === http.ResponseCode.OK) {
      if (result.status === 0) {
        return result.data as T
      }
      promptAction.showToast({ message: result.msg })
      return Promise.reject(new Error(result.msg))
    }

    promptAction.showToast({ message: '服务器异常！' })
    return Promise.reject(new Error(result.msg))
  } catch (e) {
    promptAction.showToast({ message: e })
    return Promise.reject(e)
  }
}

export class Http {
  static get<T>(url: string, data?: object, option?: { host: string }): Promise<T> {
    return requestHttp<T>(url, http.RequestMethod.GET, data, option.host)
  }

  static post<T>(url: string, data?: object, option?: { host: string }): Promise<T> {
    return requestHttp<T>(url, http.RequestMethod.POST, data, option.host)
  }

  static put<T>(url: string, data?: object, option?: { host: string }): Promise<T> {
    return requestHttp<T>(url, http.RequestMethod.PUT, data, option.host)
  }

  static delete<T>(url: string, data?: object, option?: { host: string }): Promise<T> {
    return requestHttp<T>(url, http.RequestMethod.DELETE, data, option.host)
  }
}